﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows;

namespace Sendmail.Tests
{
    public class BrokenClient
    {
        private TcpClient _client;
        private readonly string _ip;
        private readonly int _port;
        private readonly int _reps;

        public BrokenClient(string ip, int port, int reps)
        {
            _ip = ip;
            _port = port;
            _reps = reps;
        }

        public void Run(object state)
        {
            _client = new TcpClient();
            _client.Connect(new IPEndPoint(IPAddress.Parse(_ip), _port));

            try
            {
                Write("EHLO");
                Read();
                for (var i = 0; i < _reps; i++)
                {
                    try
                    {

                        Write("ble");
                    }
                    catch (Exception exception)
                    {
                        MessageBox.Show(exception.Message);
                        break;
                    }
                }
                Write("QUIT");
                Read();
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
        }

        private void Write(String strMessage)
        {
            var clientStream = _client.GetStream();
            var encoder = new ASCIIEncoding();
            var buffer = encoder.GetBytes(strMessage);
            clientStream.Write(buffer, 0, buffer.Length);
            clientStream.Flush();     
        }

        private String Read()
        {
            var messageBytes = new byte[8192];
            var clientStream = _client.GetStream();
            var encoder = new ASCIIEncoding();
            var bytesRead = clientStream.Read(messageBytes, 0, 8192);
            return encoder.GetString(messageBytes, 0, bytesRead);
        }
    }
}